<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">


    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅项目类型名称可查）"
                style="width: 20%"
                clearable></el-input>

      <el-button style="margin-left: 10px" type="primary" @click="add">新增项目类型</el-button>

      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="industryId" width="100" label="项目类型分类ID"/>
      <el-table-column sortable prop="industryName" width="220" label="项目类型名称"/>
      <el-table-column sortable prop="description" width="350" label="项目类型描述"/>
      <el-table-column sortable prop="username" width="150" label="创建人"/>
      <el-table-column sortable prop="createTime" width="250" label="创建时间"/>
      <el-table-column sortable prop="updateTime" width="250" label="修改时间"/>
      <el-table-column sortable width="250" label="状态">
        <template #default="scope">
          <span v-if="scope.row.isDeleted === 0">使用中</span>
          <span v-else>已禁用</span>
        </template>
      </el-table-column>


      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
          <el-popconfirm title="确定永久删除吗?" @confirm="deleteData(scope.row.industryId)">
            <template #reference>
              <el-button link type="primary" :icon="Delete">删 除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>


    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 15, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>
  </div>


  <div style="margin: 10px 0">
    <!--编辑弹框-->
    <div>
      <el-dialog v-model="data.editDialogVisible" title="请输入更新的信息" width="30%" center>
        <el-form :model="data.form" label-width="60px" ref="userTableFormRef">
          <el-form-item style="margin-left: 50px" label-width="80" label="项目类型">
            <el-input v-model="data.form.industryName" style="width: 80%;" placeholder="请输入项目类型"/>
          </el-form-item>
          <el-form-item style="margin-left: 50px" label-width="80" label="描   述">
            <el-input type="textarea" rows="6" v-model="data.form.description" style="width: 80%;"
                      placeholder="请输入相关描述"/>
          </el-form-item>
          <el-form-item style="margin-left: 50px" label-width="80" label="状 态">
            <div class="mb-2 flex items-center text-sm">
              <el-radio-group v-model="data.form.isDeleted" class="ml-4">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>

        <template #footer>
              <span class="dialog-footer">
                <el-button @click="data.editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确认</el-button>
              </span>
        </template>
      </el-dialog>
    </div>

    <!--新增弹框-->
    <div>
      <el-dialog v-model="data.addDialogVisible" title="请输入新增的相关信息" width="30%" center>
        <el-form :model="data.addForm" label-width="60px" ref="userTableFormRef">
          <el-form-item style="margin-left: 50px" label-width="80" label="项目类型">
            <el-input v-model="data.addForm.industryName" style="width: 80%;" placeholder="请输入项目类型"/>
          </el-form-item>
          <el-form-item style="margin-left: 50px" label-width="80" label="描   述">
            <el-input type="textarea" rows="6" v-model="data.addForm.description" style="width: 80%;"
                      placeholder="请输入相关描述"/>
          </el-form-item>
        </el-form>

        <template #footer>
              <span class="dialog-footer">
                <el-button @click="data.addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveAdd">确认</el-button>
              </span>
        </template>
      </el-dialog>
    </div>
  </div>


  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {reactive} from "vue";
import {Delete, Edit} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';

const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userData = dataString ? JSON.parse(dataString) : null;

const data = reactive({
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  selectedRows: [], // 选中行的数组
  //编辑表单
  form: {},
  //新增表单
  addForm: {
    industryName: "",
    description: "",
    creatorId: userData.userId,
  },
  //弹窗默认关闭
  editDialogVisible: false,
  //弹窗默认关闭
  addDialogVisible: false,
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  request.get(`/java/industry/category/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("页面刷新数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const deleteData = async (Id) => {
  try {
    const res = await request.delete("/java/industry/category/deleteById/" + Id);
    console.log(res);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};


//批量删除的行
const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

//批量删除
const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.industryId); // 使用 industryId 作为唯一标识
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);

  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定删除选中的选项吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    try {
      const res = await request.delete('/java/industry/category/delete/' + selectedIds);
      console.log('批量删除返回信息：', res);
      Load();
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
};

//编辑用户信息
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//让form对象独立出来，还能包含那一行的数据
  data.editDialogVisible = true;
};


const saveEdit = () => {
  data.editDialogVisible = false
  request.put(`/java/industry/category/edit`, data.form).then((res) => {
    if (res.code === 200) {
      ElMessage.info("编辑成功")
    } else {
      ElMessage.error("编辑失败")
    }
    Load();
  })
}


//打开新增的编辑框
const add = () => {
  data.addDialogVisible = true;
}

const saveAdd = () => {
  data.addDialogVisible = false
  request.post(`/java/industry/category/insertData`, data.addForm).then((res) => {
    if (res.code === 200) {
      ElMessage.info("新增成功")
    } else {
      ElMessage.error("新增失败")
    }
    Load();
  })
}

</script>
